<?php

/**
 * this class help to parse email content var and send mail directly using email function or smtp mail base on phpmailer
 */
class EmailHelper {

    /**
     * send email using newsletter template
     * @param string $receiver receiver email
     */
    public static function sendNewsletter($receiver) {

    }

    /**
     * send mail after custommer click submit contact form
     * @param mix $receiptContent array or object,
     * array('subject' => 'message', 'body' => 'body', 'email' => email, 'phone' => 'phone')
     */
    public static function sendContactRequest($receiptContent) {
        //get email template
        $mailTemplate = db()->createCommand()
                ->select('*')
                ->from('{{email_template}}')
                ->where('id = 10')
                ->queryRow();

        if (is_array($receiptContent)) {
            $subject = $receiptContent['subject'];
            $body = str_replace(array('[MESSAGE]', '[SENDER]', '[NAME]', '[PHONE]', '[MAILSUBJECT]', '[IP]', '[SITE_NAME]', '[URL]'), array(
                $receiptContent['body'],
                $receiptContent['email'],
                $receiptContent['name'],
                $receiptContent['phone'],
                $receiptContent['subject'],
                $_SERVER['REMOTE_ADDR'],
                'Contact',
                bu()
                    ), $mailTemplate['body']
            );
        } elseif (is_object($receiptContent)) {
            $subject = $receiptContent->subject;
            $body = str_replace(array('[MESSAGE]', '[SENDER]', '[NAME]', '[PHONE]', '[MAILSUBJECT]', '[IP]', '[SITE_NAME]', '[URL]'), array(
                $receiptContent->body,
                $receiptContent->email,
                $receiptContent->name,
                $receiptContent->phone,
                $receiptContent->subject,
                $_SERVER['REMOTE_ADDR'],
                'Contact',
                bu()
                    ), $mailTemplate['body']
            );
        } else {
            //model not valid
            throw new CHttpException(500, 'receiver MUST be CFormModel or array');
            return;
        }

        //send mail to admin
        $contactsetting = settings()->load('site');
        $adminEmail = db()->createCommand()
                ->select('*')
                ->from('{{admin}}')
                ->where('admin_id = :id',array(
                    ':id'=>$contactsetting['contact_id']
                ))
                ->queryRow();
        if($adminEmail){
            self::send($adminEmail['admin_email'], $subject, $body);
        }else{
            self::send($contactsetting['admin_email'], $subject, $body);
        }
    }

    /**
     * send mail to reveiver
     * @param string $receiver email
     * @param string $subject
     * @param string $body
     */
    public static function send($receipt, $subject, $body = '', $recipientName = '') {
        //reading config
        $setting = app()->settings;
        $emailConfig = $setting->load('email');
        $adminEmail = $setting->get('site', 'admin_email');
        $body = str_replace('[IP]', $_SERVER['REMOTE_ADDR'], $body);
        $body = str_replace('[SITE_NAME]', $_SERVER['HTTP_HOST'], $body);
        $body = str_replace('[URL]', app()->createAbsoluteUrl(''), $body);
        if ($emailConfig['smtp']) { //using smtp email
            //load phpmailer class
            Yii::import('common.extensions.swiftMailer.SwiftMailer');

            $mailer = new SwiftMailer;
            // Get config
            $mailHost = $emailConfig['smtp_host'];
            $mailPort = $emailConfig['smtp_port']; // Optional
            // New transport
            $Transport = $mailer->smtpTransport($mailHost, $mailPort);

            // Mailer
            $Mailer = $mailer->mailer($Transport);

            // New message
            $Message = $mailer
                    ->setContentType('text/html')
                    ->newMessage($subject)
                    ->setFrom(array($adminEmail => $adminEmail))
                    ->setTo(array($receipt => $recipientName))
                    //->addPart($content, 'text/html')
                    ->setBody($body)
            //->attach(Swift_Attachment::fromPath('my-document.pdf'))
            ;

            // Send mail
            $Mailer->send($Message);
        } else { //using email() function
            $headers = "From: " . $emailConfig['smtp_account'] . PHP_EOL . "Reply-To: " . $emailConfig['smtp_account'];
            $headers .= PHP_EOL . 'Content-type: text/html; charset=utf8' . PHP_EOL;
            //$headers = "From: {$adminEmail}\r\nReply-To: {$adminEmail}";
            mail($receipt, $subject, $body, $headers);
        }
    }

    /**
     * send mail to reveiver
     * @param string $receiver email
     * @param string $subject
     * @param string $body
     * @param string $file
     */
    public static function send_attach($receipt, $subject, $body = '', $id = '', $recipientName = '') {
        //reading config
        $setting = app()->settings;
        $emailConfig = $setting->load('email');
        $adminEmail = $setting->get('site', 'admin_email');
        $body = str_replace('[IP]', $_SERVER['REMOTE_ADDR'], $body);
        $body = str_replace('[SITE_NAME]', $_SERVER['HTTP_HOST'], $body);
        $body = str_replace('[URL]', app()->createAbsoluteUrl(''), $body);
//        if ($emailConfig['smtp']) { //using smtp email
//            //load phpmailer class
//            $message = new YiiMailMessage();
//            // Get config
//            $mailHost = $emailConfig['smtp_host'];
//            $mailPort = $emailConfig['smtp_port']; // Optional
//            // New transport
//            $Transport = $message->smtpTransport($mailHost, $mailPort);
//
//            // Mailer
//            $Mailer = $message->mailer($Transport);
//
//            // New message
//            $message->setFrom(array($adminEmail => $adminEmail))
//                    ->setTo(array($receipt => $recipientName))
//                    ->setSubject($subject)
//                    //->addPart($content, 'text/html')
//                    ->setBody($body,'text/html')
//                    ->attach(Swift_Attachment::fromPath($file))
//            ;
//
//            // Send mail
//            Yii::app()->mail->send($message);
//        } else {
        $message = new YiiMailMessage();
        $message->setTo(array($receipt => $recipientName));
        $message->setFrom(array($adminEmail => $adminEmail));
        $message->setSubject($subject);
        $message->setBody($body, 'text/html');
        $file = ReportFile::model()->findAll('order_id=:id', array(':id' => $id));
        if ($file) {
            foreach ($file as $value){
                $message->attach(Swift_Attachment::fromPath(REPORT_PATH.$value->report_file));
            }
        }
        Yii::app()->mail->send($message);
        //}
    }

}